module MenusHelper
  def load_menu
    @menus = []
    return unless current_user

    personal_center = {
      name: ts(:personal, :center),
      icon_class: 'si si-home',
      children: []
    }
    personal_center[:children] = [
      {
        name:  Sales::Firm.model_name.human,
        url: sales_firms_path
      }
    ]
    @menus << personal_center
  end

  def set_current_menu
    @menus.each do |m|
      if url_current?(m[:url]) && m[:children].blank?
        m[:current] = true
        @current_menu_group = m
        # 指向了菜单则保存到session
        session[:last_menu] = m[:url]
        break
      end
      m[:children].each do |c|
        next unless url_current?(c[:url])
        c[:current] = true
        m[:current] = true
        @current_menu_group = m
        # 指向了菜单则保存到session
        session[:last_menu] = c[:url]
        break
      end
    end
    if @current_menu_group.blank?
      @menus.each do |m|
        if url_current?(m[:url], session[:last_menu]) && m[:children].blank?
          m[:current] = true
          @current_menu_group = m
          break
        end
        m[:children].each do |c|
          next unless url_current?(c[:url], session[:last_menu])
          c[:current] = true
          m[:current] = true
          @current_menu_group = m
          break
        end
      end
      @current_menu_group ||= @menus.first
    end
  end

  def url_current?(link_url, request_url = request.url)
    return true if request_url == link_url || request_url.to_s.end_with?(link_url.to_s)
    # 切开来判断
    link_base = link_url.split('?').first
    link_params = link_url.split('?')[1].to_s.split('&').sort
    request_base = request.path
    request_params = request.query_string.to_s.split('&').sort
    link_base == request_base && link_params == request_params
  end
end
